package com.yunda.nebula.gateway.sync.http;

import com.yunda.nebula.gateway.core.DataSubscriber;
import com.yunda.nebula.gateway.core.entity.ConfigData;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

/**
 * \* User: wei.zhang
 * \* Date: 2020/9/16 17:15
 * \* Description:
 *
 * @author wei.zhang
 * \
 */
@Data
@Slf4j
public class AppDataRefresh implements DataRefresh {

    private List<DataSubscriber> dataSubscriberList;

    private ConfigData configData;

    @Override
    public Boolean refresh(ConfigData data) {
        if (configData != null) {
            String key = configData.getMd5() + data.getLastModifyTime();
            String newKey = data.getMd5() + data.getLastModifyTime();
            if (key.equalsIgnoreCase(newKey)) {
                log.info("缓存版本一致,不需要更新 !!!,appid 为 {}",configData);
                return false;
            } else {
                this.configData = data;
                log.info("缓存版本不一致,开始呢更新 !!!,appid 为 {}",configData);
                subscribe(data);
                return true;
            }
        }else {

            this.configData = data;
            subscribe(data);
            return true;
        }
    }

    public void subscribe(ConfigData data){
       if (CollectionUtils.isNotEmpty(dataSubscriberList)){
           dataSubscriberList.forEach(dataSubscriber -> {
               dataSubscriber.refresh(data);
           });
       }
    }

    @Override
    public ConfigData cacheConfigData() {
        return configData;
    }

    @Override
    public boolean del() {
        configData = null;
        return true;
    }
}
